package com.jams.goodox.activity.wallet;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hangzhou.jin.customview.SuperText;
import com.hangzhou.jin.customview.TitleView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.common.SimpleHtmlActivity;
import com.jams.goodox.constant.Constant;
import com.jams.goodox.constant.H5UrlConstants;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * Created by Jin on 2016/12/26.
 * Description 设置（重置）支付密码 page1
 */
public class SetPayPasswordActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TitleView mTitleView;
    @Bind(R.id.mid_content)
    TextView mMidContent;
    @Bind(R.id.protocol_check)
    ImageView check;
    @Bind(R.id.verification_code)
    EditText code;
    @Bind(R.id.confirm_pay)
    TextView confirmPay;
    @Bind(R.id.verification_code_btn)
    TextView sendCode;
    @Bind(R.id.phone)
    SuperText phoneView;
    @Bind(R.id.mask)
    RelativeLayout mask;
    @Bind(R.id.check_view)
    LinearLayout checkView;

    //协议是否同意
    private boolean hasCheck = false;

    // 密码框长度输入限制
    public static final int INPUT_LENGTH_LIMIT = 6;

    private String phone;
    public static final String FromType = "FromType";
    private int fromType;//301:个人 302：企业

    @Override
    protected int getLayoutId() {
        return R.layout.set_pay_password;
    }

    @Override
    protected void init() {
        setTitleVisibility(false);
        phone = DataCacheManager.getInstance().getUser() != null ? DataCacheManager.getInstance().getUser().getMobileNum() : "";
        fromType = getIntent().getIntExtra(FromType, 0);
        if (SePref.isSetPayPwd()) {
            mTitleView.setTitle("重置支付密码");
            mMidContent.setText("重置支付密码");
            checkView.setVisibility(View.GONE);
        }

        phoneView.setText(phone);
        if (!SePref.isSetPayPwd() && fromType == 302) {
            Utils.doFunctionIsOpen(this, Constant.AppFunctionName.Company_First_Set_Pwd,R.string.first_set_company_pay_pwd);
        }
    }

    @OnClick({R.id.verification_code_btn, R.id.protocol_check_layout, R.id.protocol, R.id.confirm_pay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.verification_code_btn:
                sendCode();
                break;
            case R.id.protocol_check_layout:
                hasCheck = !hasCheck;
                check.setBackground(hasCheck ? ContextCompat.getDrawable(this, R.mipmap.check_active) : ContextCompat.getDrawable(this, R.mipmap.uncheck_active));
                break;
            case R.id.protocol:
                Bundle b = new Bundle();
                b.putString(SimpleHtmlActivity.URL, H5UrlConstants.H5_Agreement);
                b.putString(SimpleHtmlActivity.TITLE, "安全协议");
                qBackToActivity(SimpleHtmlActivity.class, b);
                break;
            case R.id.confirm_pay:
                if (code.getText().length() == INPUT_LENGTH_LIMIT) {
                    // 重置页面不需要同意协议
                    if (hasCheck || SePref.isSetPayPwd()) {
                        verifyCode();
                    } else {
                        ToastUtil.show(SetPayPasswordActivity.this, "请同意安全协议");
                    }
                } else {
                    ToastUtil.show(SetPayPasswordActivity.this, "请输入验证码");
                }
                break;
        }
    }

    private void verifyCode() {
        closeKeyboard();

        mask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 空方法覆盖底层的点击事件
            }
        });
        mask.setVisibility(View.VISIBLE);
        final String codeText = code.getText().toString();
        enqueue(createCallService(MineService.class).verifyCode(phone, codeText), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                Bundle b = new Bundle();
                b.putString("code", codeText);
//				b.putInt("come", getIntent().getIntExtra("come", 0));
                qStartActivity(SetPayPassword2Activity.class, b);
                mask.setVisibility(View.GONE);
                finish();
            }

            @Override
            public void onError(String msg) {
                mask.setVisibility(View.GONE);
            }
        });
    }


    /* 定义一个倒计时的内部类 */
    class MyCount extends CountDownTimer {
        /**
         * @param millisInFuture    总计
         * @param countDownInterval 间隔
         */
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            sendCode.setClickable(true);
            sendCode.setBackgroundResource(R.drawable.bg_cancel_theme);
            sendCode.setText("获取验证码");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            sendCode.setText(millisUntilFinished / 1000 + "秒后重发");
        }
    }

    /**
     * 发送验证码
     */
    private void sendCode() {
        if (Utils.isPhoneNum(phone)) {
            // 阻止重复点击
            sendCode.setClickable(false);
            sendCode.setBackgroundResource(R.drawable.bottom_btn_2dp_grey);
            enqueue(createCallService(MineService.class).sendPayCode(phone), new RetrofitCallbackListener<BaseEntity>() {
                @Override
                public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                    ToastUtil.showShort(SetPayPasswordActivity.this, "验证码已经发送");

                    sendCode.setText("60秒后重发");
                    sendCode.setBackgroundResource(R.drawable.bottom_btn_2dp_grey);

                    MyCount count = new MyCount(60000, 1000);
                    count.start();
                }

                @Override
                public void onError(String msg) {
                    sendCode.setClickable(true);
                    sendCode.setBackgroundResource(R.drawable.bg_cancel_theme);
                }
            });
        } else {
            ToastUtil.show(SetPayPasswordActivity.this, "请输入11位手机号");
        }
    }
}
